import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 跳转白名单，无需鉴权
// const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  const userInfo = store.getters.user

  if (to.meta.auth) {
    // 需要鉴权
    // 1.查看是否有用户信息
    if (userInfo) {
      next()
    } else {
      // 2.查看是否有token
      const token = localStorage.getItem('adminToken')
      if (token) {
        // 3.验证token有效性
        const resp = await store.dispatch('user/getInfo')
        if (resp.code === 401) {
          await store.dispatch('user/resetToken')
          Message.error('登录状态已过期，请重新登录')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        } else {
          next()
        }
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    // 无需鉴权
    if (to.path === '/login' && userInfo) {
      next({ path: '/' })
    } else {
      next()
    }
    NProgress.done()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
